﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking; //注意引用命名控件

public class D09_UnityWebRequest : MonoBehaviour
{
    private AsyncOperation asyncOperation;
    private void OnGUI()
    {
        if (GUILayout.Button("访问百度"))
        {
            StartCoroutine(Test());
        }

        if (GUILayout.Button("下载图片"))
        {
            StartCoroutine(Test1());
        }
    }

    private IEnumerator Test()
    {
        //构造一个请求对象
        UnityWebRequest req = UnityWebRequest.Get("https://baidu.com"); //get 一般用于下载,  post一般用于提交表单,传给服务器键值对, put一般用来上传文件

        //可以在这里更换req的DownLoadHander

        var async = req.SendWebRequest();//发起请求
        yield return async; //等待async的progress到1的时候才会继续往下执行
        print(req.downloadHandler.text);
    }

    private IEnumerator Test1()
    {
        //构造一个请求对象
        UnityWebRequest req = UnityWebRequest.Get("https://unity-cn-cdn-prd.unitychina.cn/assets/styles/i/cn/releases/banner1.bf3f429497e76b15df02e73d6dec293d.jpg"); //get 一般用于下载,  post一般用于提交表单,传给服务器键值对, put一般用来上传文件

        req.downloadHandler = new DownloadHandlerTexture();

        asyncOperation = req.SendWebRequest();//发起请求
        yield return asyncOperation; //等待async的progress到1的时候才会继续往下执行

        DownloadHandlerTexture downloadHandler = req.downloadHandler as DownloadHandlerTexture;
        GetComponent<MeshRenderer>().material.mainTexture = downloadHandler.texture;
    }

    private void Update()
    {
        if (asyncOperation != null)
        {
            print(asyncOperation.progress);//显示进度
        }
    }
}